<template>
  <div class="tu-toolbar-content">
    <div
      class="tu-toolbar-icon"
      @click="refreshData"
    >
      <el-icon>
        <Refresh />
      </el-icon>
    </div>
    <el-popover
      placement="right"
      trigger="click"
    >
      <template #reference>
        <div class="tu-toolbar-icon">
          <el-icon>
            <Menu />
          </el-icon>
        </div>
      </template>
      <el-tree
        ref="treeRef"
        :data="treeList"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="activeIds"
        :props="defaultProps"
        @check-change="handleCheckedChange"
      />
    </el-popover>

  </div>
</template>

<script lang='ts' setup>
import { Refresh, Menu } from '@element-plus/icons-vue';
import { ref } from 'vue';
import type { tableHeaderType } from '../TableType'

const props = defineProps<{
  tableHeader: tableHeaderType[]
  activeIds: string[]
}>()

const emits = defineEmits<{
  (e: 'refreshData'): void
  (e: 'updateTableColumn', columnId: string, heidden: boolean): void
}>()

// 数实例
const treeRef = ref()

// 多选框组
const treeList = ref<tableHeaderType[]>([])
const defaultProps = {
  children: 'children',
  label: 'label',
}
treeList.value = JSON.parse(JSON.stringify(props.tableHeader))

// 多选框 change 事件
const handleCheckedChange = (item: tableHeaderType, heidden: boolean) => {
  if (!item?.children?.length && lock) {
    emits('updateTableColumn', item?.id as string, heidden)
  }
}

/**
 * 刷新数据
 */
const refreshData = () => {
  emits('refreshData')
}

/**
 * 返回选中的id
 */
const getCheckedKeys = () => {
  if (treeRef.value) {
    return [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()]
  } else {
    return []
  }
}

let lock = true
/**
 * 设置某个节点的选中状态
 */
const setChecked = (id: string) => {
  lock = false

  treeRef.value.setChecked(id, true, true)
  // 加延迟锁防止触发change事件
  setTimeout(() => {
    lock = true
  }, 500)
}

defineExpose({
  getCheckedKeys,
  setChecked
})
</script>

<style scoped lang='scss'>
.tu-toolbar-content {
  display: flex;
  border: 1px solid #dcdfe6;
  border-radius: 4px;

  .tu-toolbar-icon {
    width: 38px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    color: #6b6b6b;
    border-right: 1px solid #dcdfe6;
    cursor: pointer;
  }

  .tu-toolbar-icon:last-child {
    border-right: none;
  }
}
</style>